<template>
  <div class="admin-dashboard">
    <!-- 顶部导航 -->
    <el-header class="admin-header">
      <div class="header-content">
        <div class="logo">
          <i class="el-icon-s-platform"></i>
          <span>后台管理系统</span>
        </div>
        <div class="user-info">
          <span>管理员: {{ adminName }}</span>
          <el-button size="small" @click="logout">退出</el-button>
        </div>
      </div>
    </el-header>

    <!-- 主要内容 -->
    <el-main class="admin-main">
      <!-- 系统概览 -->
      <el-row :gutter="20" class="overview-cards">
        <el-col :span="6" v-for="(item, key) in overview" :key="key">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon">
                <i :class="getCardIcon(key)"></i>
              </div>
              <div class="card-info">
                <div class="card-value">{{ item }}</div>
                <div class="card-label">{{ getCardLabel(key) }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 数据筛选 -->
      <el-card class="filter-card">
        <div slot="header" class="clearfix">
          <span><i class="el-icon-data-analysis"></i> 数据统计</span>
        </div>
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="开始日期">
            <el-date-picker
              v-model="filterForm.startDate"
              type="date"
              placeholder="选择开始日期"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker
              v-model="filterForm.endDate"
              type="date"
              placeholder="选择结束日期"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadStats" :loading="loadingStats">
              <i class="el-icon-search"></i> 查询
            </el-button>
            <el-button type="success" @click="exportExcel" :loading="exporting">
              <i class="el-icon-download"></i> 导出Excel
            </el-button>
			<el-button type="warning" @click="showAddAccountDialog" :loading="addingAccount">
			    <i class="el-icon-circle-plus"></i> 添加账号
			  </el-button>
          </el-form-item>
		  
        </el-form>
		
      </el-card>

      <!-- 数据表格 -->
      <!-- 数据表格 -->
          <el-card class="data-card">
            <div slot="header" class="clearfix">
              <span><i class="el-icon-tickets"></i> 任务提交明细</span>
            </div>
            <el-table
              :data="statsData"
              v-loading="loadingStats"
              style="width: 100%"
              :default-sort="{prop: 'submitTime', order: 'descending'}">
              
              <!-- <el-table-column prop="date" label="日期" width="100" sortable>
                <template slot-scope="scope">
                  {{ formatDate(scope.row.submitTime, 'yyyy-MM-dd') }}
                </template>
              </el-table-column> -->
              <el-table-column prop="type" label="用户" width="100"></el-table-column>
              <el-table-column prop="username" label="用户" width="100"></el-table-column>
              <el-table-column prop="account" label="账号" width="120"></el-table-column>
              <el-table-column prop="level" label="等级" width="100"></el-table-column>
              
              <!-- 截图列 -->
              <el-table-column label="截图1" width="120">
                <template slot-scope="scope">
                  <div v-if="scope.row.screenshotPaths && scope.row.screenshotPaths[0]">
                    <el-image
                      style="width: 80px; height: 60px; cursor: pointer;"
                      :src="getImageUrl(scope.row.screenshotPaths[0],scope.row.type)"
                      :preview-src-list="getPreviewList(scope.row.screenshotPaths,scope.row.type)"
                      fit="cover"
                      :preview-teleported="true">
                      <div slot="error" class="image-error">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </el-image>
                  </div>
                  <span v-else class="no-image">无截图</span>
                </template>
              </el-table-column>
      
              <el-table-column label="截图2" width="120">
                <template slot-scope="scope">
                  <div v-if="scope.row.screenshotPaths && scope.row.screenshotPaths[1]">
                    <el-image
                      style="width: 80px; height: 60px; cursor: pointer;"
                      :src="getImageUrl(scope.row.screenshotPaths[1],scope.row.type)"
                      :preview-src-list="getPreviewList(scope.row.screenshotPaths,scope.row.type)"
                      fit="cover"
                      :preview-teleported="true">
                      <div slot="error" class="image-error">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </el-image>
                  </div>
                  <span v-else class="no-image">无截图</span>
                </template>
              </el-table-column>
      
              <el-table-column label="截图3" width="120">
                <template slot-scope="scope">
                  <div v-if="scope.row.screenshotPaths && scope.row.screenshotPaths[2]">
                    <el-image
                      style="width: 80px; height: 60px; cursor: pointer;"
                      :src="getImageUrl(scope.row.screenshotPaths[2],scope.row.type)"
                      :preview-src-list="getPreviewList(scope.row.screenshotPaths,scope.row.type)"
                      fit="cover"
                      :preview-teleported="true">
                      <div slot="error" class="image-error">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </el-image>
                  </div>
                  <span v-else class="no-image">无截图</span>
                </template>
              </el-table-column>
      
              <el-table-column label="截图4" width="120">
                <template slot-scope="scope">
                  <div v-if="scope.row.screenshotPaths && scope.row.screenshotPaths[3]">
                    <el-image
                      style="width: 80px; height: 60px; cursor: pointer;"
                      :src="getImageUrl(scope.row.screenshotPaths[3],scope.row.type)"
                      :preview-src-list="getPreviewList(scope.row.screenshotPaths,scope.row.type)"
                      fit="cover"
                      :preview-teleported="true">
                      <div slot="error" class="image-error">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </el-image>
                  </div>
                  <span v-else class="no-image">无截图</span>
                </template>
              </el-table-column>
      
              <!-- 收款码列 -->
              <el-table-column label="收款码" width="120">
                <template slot-scope="scope">
                  <div v-if="scope.row.paymentCodePath">
                    <el-image
                      style="width: 80px; height: 80px; cursor: pointer;"
                      :src="getImageUrl(scope.row.paymentCodePath,scope.row.type)"
                      fit="contain"
                      :preview-src-list="[getImageUrl(scope.row.paymentCodePath,scope.row.type)]"
                      :preview-teleported="true">
                      <div slot="error" class="image-error">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </el-image>
                  </div>
                  <span v-else class="no-image">无收款码</span>
                </template>
              </el-table-column>
      
              <el-table-column prop="status" label="状态" width="100">
                <template slot-scope="scope">
                  <el-tag :type="getStatusType(scope.row.status)" size="small">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
      
              <el-table-column prop="submitTime" label="提交时间" width="160" sortable>
                <template slot-scope="scope">
                  {{ formatDate(scope.row.submitTime) }}
                </template>
              </el-table-column>
      
              <el-table-column label="操作" width="120" fixed="right">
                <template slot-scope="scope">
                  <el-button 
                    size="mini" 
                    type="primary" 
                    @click="handleReview(scope.row)"
                    v-if="scope.row.status === 'pending'">
                    审核
                  </el-button>
                  <span v-else>已审核</span>
                </template>
              </el-table-column>
            </el-table>
      
            <!-- 分页 -->
            <el-pagination
              class="pagination"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total">
            </el-pagination>
          </el-card>
      <!-- 添加账号对话框 -->
      <el-dialog
        title="添加账号"
        :visible.sync="addAccountDialogVisible"
        width="400px">
        <el-form :model="addAccountForm" label-width="80px">
          <el-form-item label="账号">
            <el-input v-model="addAccountForm.account" placeholder="请输入账号"></el-input>
          </el-form-item>
          
          <el-form-item label="密码">
            <el-input v-model="addAccountForm.password" placeholder="请输入密码"></el-input>
          </el-form-item>
        </el-form>
        
        <div slot="footer" class="dialog-footer">
          <el-button @click="addAccountDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addAccount">确定</el-button>
        </div>
      </el-dialog>
	  
          <!-- 审核对话框 -->
          <el-dialog
            title="任务审核"
            :visible.sync="reviewDialogVisible"
            width="50%">
            <div v-if="currentReview">
              <el-form label-width="80px">
                <el-form-item label="用户账号" v-if="currentReview.type=='steam'">
                  <el-tag>{{ currentReview.account }} 登录密码 {{currentReview.passWord}}</el-tag>
                </el-form-item>
				<el-form-item label="用户账号" v-if="currentReview.type=='steam2'">
				  <el-tag>卡号：卡号：{{ currentReview.account }}  卡密：{{currentReview.passWord}}--</el-tag>
				</el-form-item>
				<el-form-item label="等级">
				  <el-tag>{{ currentReview.level }}</el-tag>
				</el-form-item>
				<el-form-item label="类型">
				  <el-tag>{{ currentReview.type }}</el-tag>
				</el-form-item>
				<el-form-item label="UID" v-if="currentReview.uid">
				  <el-tag>{{ currentReview.uid }}</el-tag>
				</el-form-item>
                <el-form-item label="提交时间">
                  {{ formatDate(currentReview.submitTime) }}
                </el-form-item>
                <el-form-item label="任务截图">
                  <el-row :gutter="10">
                    <el-col :span="6" v-for="(path, index) in currentReview.screenshotPaths" :key="index">
                      <el-image
                        style="width: 100%; height: 100px; margin-bottom: 10px;"
                        :src="getImageUrl(path,currentReview.type)"
                        fit="cover"
                        :preview-src-list="getPreviewList(currentReview.screenshotPaths,currentReview.type)">
                      </el-image>
                      <div class="image-label">截图 {{ index + 1 }}</div>
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item label="收款码">
                  <el-image
                    style="width: 200px; height: 200px;"
                    :src="getImageUrl(currentReview.paymentCodePath,currentReview.type)"
                    fit="contain">
                  </el-image>
                </el-form-item>
                <el-form-item label="审核状态">
                  <el-radio-group v-model="reviewStatus">
                    <el-radio label="approved">通过</el-radio>
                    <el-radio label="rejected">拒绝</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" v-if="reviewStatus === 'rejected'">
                  <el-input
                    type="textarea"
                    v-model="reviewRemark"
                    placeholder="请输入拒绝原因"
                    :rows="3">
                  </el-input>
                </el-form-item>
              </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="reviewDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitReview(currentReview.type)">确定</el-button>
            </span>
          </el-dialog>
		  </el-main>
        </div>
      </template>

<script>
import requests from '@/utils/request';

export default {
  name: 'AdminDashboard',
  data() {
    return {
      adminName: '管理员',
      overview: {
        totalUsers: 0,
        totalSubmissions: 0,
        completedSubmissions: 0,
        totalAccounts: 0,
        assignedAccounts: 0,
        totalIncome: 0,
        todayNewUsers: 0,
        todaySubmissions: 0
      },
      filterForm: {
        startDate: this.getDefaultStartDate(),
        endDate: this.getDefaultEndDate()
      },
      statsData: [],
            loadingStats: false,
            pagination: {
              currentPage: 1,
              pageSize: 10,
              total: 0
            },
            reviewDialogVisible: false,
            currentReview: null,
            reviewStatus: 'approved',
            reviewRemark: '',
      loadingStats: false,
      exporting: false,
	  addAccountDialogVisible: false,
	      addAccountForm: {
	        account: '',
	        password: ''
	      }
    };
  },
  mounted() {
    this.loadOverview();
    this.loadStats();
  },
  methods: {
	  // 显示添加账号对话框
	    showAddAccountDialog() {
	      this.addAccountDialogVisible = true;
	      // 清空表单
	      this.addAccountForm.account = '';
	      this.addAccountForm.password = '';
	    },
	    
	    // 添加账号
	    async addAccount() {
	      if (!this.addAccountForm.account || !this.addAccountForm.password) {
	        this.$message.warning('请输入账号和密码');
	        return;
	      }
	      
	      try {
	        const response = await requests.post('/api/admin/add-account', this.addAccountForm);
	        
	        if (response.code === 200) {
	          this.$message.success('账号添加成功');
	          this.addAccountDialogVisible = false;
	          
	          // 刷新数据
	          this.loadStats();
	        } else {
	          this.$message.error(response.msg || '添加账号失败');
	        }
	      } catch (error) {
	        this.$message.error('添加账号失败: ' + (error.response?.data?.message || error.message));
	      }
	    },
    // 获取默认开始日期（昨天）
    getDefaultStartDate() {
      const date = new Date();
      date.setDate(date.getDate() - 1);
      return this.formatDate(date, 'yyyy-MM-dd');
    },
    
    // 获取默认结束日期（昨天）
    getDefaultEndDate() {
		const date = new Date();
		date.setDate(date.getDate());
      return this.formatDate(date, 'yyyy-MM-dd');
    },
    
    // 加载系统概览
    async loadOverview() {
      try {
        const response = await requests.get('/api/admin/overview');
        this.overview = response.data;
      } catch (error) {
        this.$message.error('加载系统概览失败');
      }
    },
    
    // 加载统计数据
    async loadStats() {
          if (!this.filterForm.startDate || !this.filterForm.endDate) {
            this.$message.warning('请选择开始和结束日期');
            return;
          }
          
          this.loadingStats = true;
          try {
            const response = await requests.get('/api/admin/task-submissions', {
              params: {
                startDate: this.filterForm.startDate,
                endDate: this.filterForm.endDate,
                page: this.pagination.currentPage,
                size: this.pagination.pageSize
              }
            });
            this.statsData = response.data.list || response.data;
            this.pagination.total = response.data.total || response.data.length;
          } catch (error) {
            this.$message.error('加载数据失败');
            console.error('加载数据错误:', error);
          } finally {
            this.loadingStats = false;
          }
        },
    
        // 获取图片完整URL
        getImageUrl(path,type) {
			console.log("type=",type)
          if (!path) return '';
          // 处理路径中的反斜杠
          const normalizedPath = path.replace(/\\/g, '/')
							.split('/')
                            .map(segment => encodeURIComponent(segment))
                            .join('/');
		  if(type==='steam'){
			  return `http://localhost:8088/api/files/steam/${normalizedPath}`;
			  // return `http://3.101.150.9:8088/api/files/steam/${normalizedPath}`;
		  }
		  else{
			  return `http://localhost:8088/api/files/qq/${normalizedPath}`;
			  // return `http://3.101.150.9:8088/api/files/qq/${normalizedPath}`;
		  }
        },
    
        // 获取预览图片列表
        getPreviewList(paths,type) {
          if (!paths || !Array.isArray(paths)) return [];
          return paths.map(path => this.getImageUrl(path,type)).filter(url => url);
        },
    
        // 状态显示
        getStatusText(status) {
          const statusMap = {
            'pending': '待审核',
            'approved': '已通过',
            'rejected': '已拒绝',
            'paid': '已支付'
          };
          return statusMap[status] || status;
        },
    
        getStatusType(status) {
          const typeMap = {
            'pending': 'warning',
            'approved': 'success',
            'rejected': 'danger',
            'paid': 'primary'
          };
          return typeMap[status] || 'info';
        },
    
        // 审核操作
        handleReview(row) {
          this.currentReview = { ...row };
          this.reviewStatus = 'approved';
          this.reviewRemark = '';
          this.reviewDialogVisible = true;
        },
    
        async submitReview(type) {
          try {
			  if(type==='steam'){
				  await requests.post('/api/admin/review-submission', {
				    id: this.currentReview.id,
				    status: this.reviewStatus,
				    remark: this.reviewRemark
				  });
			  }
            else{
				await requests.post('/api/admin/review-qq-submission', {
				  id: this.currentReview.id,
				  status: this.reviewStatus,
				  remark: this.reviewRemark
				});
			}
            
            this.$message.success('审核完成');
            this.reviewDialogVisible = false;
            this.loadStats(); // 重新加载数据
          } catch (error) {
            this.$message.error('审核失败');
          }
        },
    
        handleSizeChange(size) {
          this.pagination.pageSize = size;
          this.loadStats();
        },
    
        handleCurrentChange(page) {
          this.pagination.currentPage = page;
          this.loadStats();
        },

    
    // 导出Excel
async exportExcel() {
  if (!this.filterForm.startDate || !this.filterForm.endDate) {
    this.$message.warning('请选择开始和结束日期');
    return;
  }
  
  this.exporting = true;
  try {
    const params = new URLSearchParams({
      startDate: this.filterForm.startDate,
      endDate: this.filterForm.endDate
    });
    // 使用新的包含图片的导出接口
    window.open(`http://localhost:8088/api/admin/export-excel-with-images?${params.toString()}`);
    // window.open(`http://3.101.150.9:8088/api/admin/export-excel-with-images?${params.toString()}`);
    this.$message.success('导出任务已开始，请查看下载');
  } catch (error) {
    this.$message.error('导出失败: ' + error.message);
  } finally {
    this.exporting = false;
  }
},
    
    // 获取卡片图标
    getCardIcon(key) {
      const icons = {
        totalUsers: 'el-icon-user-solid',
        totalSubmissions: 'el-icon-document',
        completedSubmissions: 'el-icon-success',
        totalAccounts: 'el-icon-key',
        assignedAccounts: 'el-icon-check',
        totalIncome: 'el-icon-money',
        todayNewUsers: 'el-icon-user',
        todaySubmissions: 'el-icon-upload2'
      };
      return icons[key] || 'el-icon-data-line';
    },
    
    // 获取卡片标签
    getCardLabel(key) {
      const labels = {
        totalUsers: '总用户数',
        totalSubmissions: 'steam1总提交数',
        completedSubmissions: 'steam1完成数',
        totalAccounts: 'steam1总账号数',
        assignedAccounts: 'steam1已分配账号',
        totalIncome: '总收入',
        todayNewUsers: '今日新增',
        todaySubmissions: '今日提交',
		steam2TotalSubmissions:'steam2提交数',
		steam2TotalAccounts:'steam2账号数',
		steam2AssignedAccounts:'steam2已分配账号',
		steam2CompletedSubmissions:'steam2完成数'
      };
      return labels[key] || key;
    },
    
    // 格式化日期
    formatDate(date, format = 'yyyy-MM-dd HH:mm:ss') {
      if (!date) return '';
      const d = new Date(date);
      const pad = n => n.toString().padStart(2, '0');
      
      return format
        .replace('yyyy', d.getFullYear())
        .replace('MM', pad(d.getMonth() + 1))
        .replace('dd', pad(d.getDate()))
        .replace('HH', pad(d.getHours()))
        .replace('mm', pad(d.getMinutes()))
        .replace('ss', pad(d.getSeconds()));
    },
    
    // 退出登录
    logout() {
      localStorage.removeItem('adminToken');
      this.$router.push('/admin/login');
    }
  }
};
</script>

<style scoped>
.admin-dashboard {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.admin-header {
  background: linear-gradient(to right, #409EFF, #67C23A);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  color: white;
}

.logo {
  font-size: 20px;
  font-weight: bold;
}

.logo i {
  margin-right: 10px;
}

.admin-main {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  margin-bottom: 20px;
}

.card-content {
  display: flex;
  align-items: center;
}

.card-icon {
  font-size: 40px;
  color: #409EFF;
  margin-right: 15px;
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.card-label {
  color: #909399;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  margin-bottom: -18px;
}

.data-card {
  margin-bottom: 20px;
}
</style>